﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using EntitiesTM;
using Business;
using System.Data;

namespace TimeWork
{
    public partial class ViewProject : System.Web.UI.Page
    {
        private string getParam()
        {
            if (Request.QueryString["pid"] != null)
            {
                return Request.QueryString["pid"].ToString();
            }
            else
            {
                return "0";
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["email"] == null)
            {
                Response.Redirect("http://"+Request.Url.Authority+"/Login.aspx");
            }
            if (!IsPostBack)
            {
                //pnlCopy.Visible = false;
                fillCopyActivity();
                fillProject();
                fillActivity();
                fillProjectMember();
                fillTimeUser();
            }
        }

        private void hidePanel(bool activity, bool projectMember, bool reportTime)
        {
            pnlActivity.Visible = activity;
            pnlProjectMember.Visible = projectMember;
            pnlReportTime.Visible = reportTime;
        }

        private void fillProject()
        {
            // Lay projectID qua tham so pid
            int projectID = Int32.Parse(getParam());
            // Truong hop sua project
            if (projectID != 0)
            {
                btnCreateProject.Visible = false;
                btnDelete.Visible = true;
                btnUpdate.Visible = true;
                EnProject project = BuProject.selProjectByID(projectID, Session["companyid"].ToString());

                // Fill du lieu vao cac control
                txtProjectName.Text = project.projectName;
                // Dua danh sach nguoi dung vao dropdownlist
                ddlProjectManager.DataSource = BuStaff.selAllStaffOpt(Session["companyid"].ToString());
                ddlProjectManager.DataTextField = "StaffName";
                ddlProjectManager.DataValueField = "StaffID";
                ddlProjectManager.DataBind();
                ddlProjectManager.SelectedValue = project.staffID.ToString();

                // Fill dropdownlist Client
                DataTable dataClient = BuClient.selAllClient(Session["companyid"].ToString());
                if (dataClient.Rows.Count != 0)
                {
                    ddlClient.DataSource = dataClient;
                    ddlClient.DataTextField = "ClientName";
                    ddlClient.DataValueField = "ClientID";
                    ddlClient.DataBind();
                    ddlClient.Items.Insert(0, new ListItem("--- Chọn đối tác ---", "0"));

                    if (project.projectClientID != 0)
                    {
                        ddlClient.SelectedValue = project.projectClientID.ToString();
                    }
                    else
                    {
                        ddlClient.SelectedValue = "0";
                    }
                }
                else
                {
                    ddlClient.DataBind();
                    ddlClient.Items.Insert(0, new ListItem("--- Chọn đối tác ---", "0"));
                    ddlClient.SelectedValue = "0";
                }

                // Fill Checkbox
                cbIsComplete.Checked = project.projectEnable;
                cbIsMember.Checked = project.projectEnableMember;
                txtDescription.Text = project.projectDescription;
                txtStartDay.Text = project.projectStartDate.ToString("dd/MM/yyyy");
                txtEndDay.Text = project.projectEndDate.ToString("dd/MM/yyyy");

                // Hien bieu do
                string result = BuChart.selChartAccProject(projectID, Session["companyid"].ToString());
                if (!result.Equals(""))
                {
                    imgChartAccu.ImageUrl = result;
                }
            }

            // Truong hop tao moi project
            else
            {
                // An cac panel khac
                hidePanel(false, false, false);

                btnCreateProject.Visible = true;
                btnDelete.Visible = false;
                btnUpdate.Visible = false;
                // Khoi tao gia tri mac dinh
                // Dua danh sach nguoi dung vao dropdownlist
                ddlProjectManager.DataSource = BuStaff.selAllStaffOpt(Session["companyid"].ToString());
                ddlProjectManager.DataTextField = "StaffName";
                ddlProjectManager.DataValueField = "StaffID";
                ddlProjectManager.DataBind();

                // Client
                DataTable dataClient = BuClient.selAllClient(Session["companyid"].ToString());
                if (dataClient.Rows.Count != 0)
                {
                    ddlClient.DataSource = dataClient;
                    ddlClient.DataTextField = "ClientName";
                    ddlClient.DataValueField = "ClientID";
                }
                ddlClient.DataBind();
                ddlClient.Items.Insert(0, new ListItem("--- Chọn đối tác ---", "0"));
                ddlClient.SelectedValue = "0";

                txtStartDay.Text = DateTime.Today.ToString("dd/MM/yyyy");
                txtEndDay.Text = DateTime.Today.ToString("dd/MM/yyyy");
            }
        }

        // Tao moi project
        protected void btnCreateProject_Click(object sender, EventArgs e)
        {
            string nameProject = txtProjectName.Text.Trim();
            if (nameProject.Equals(""))
            {
                // Truong hop bo trong ten project
                txtProjectName.CssClass = "input-error";
                lblError.Text = "Không được bỏ trống!";
            }
            else
            {
                // Lay cac tham so
                int projectManager = Int32.Parse(ddlProjectManager.SelectedValue);
                int clientID = Int32.Parse(ddlClient.SelectedValue);
                string projectDescription = txtDescription.Text;
                bool isMember = cbIsMember.Checked;
                bool isComplete = cbIsComplete.Checked;
                string startDate = txtStartDay.Text;
                string endDate = txtEndDay.Text;

                // Chay cac thu thu tuc
                EnProject project = new EnProject();
                project.projectName = nameProject;
                project.projectDescription = projectDescription;
                project.projectClientID = clientID;
                project.projectStartDate = DateTime.ParseExact(startDate, "dd/MM/yyyy", null);
                project.projectEndDate = DateTime.ParseExact(endDate, "dd/MM/yyyy", null);
                project.projectEnable = isComplete;
                project.projectEnableMember = isMember;
                project.projectManager = projectManager;
                BuProject.insProject(project, Session["companyid"].ToString());

                //EnSP sp = new EnSP();
                //sp.spStaffID = projectManager;
                //sp.spCostPerHour = 0;
                //BuProject.insSP(sp);

                Response.Redirect("~/time/admin/ViewProject.aspx?pid=" + BuProject.selTopProjectID(Session["companyid"].ToString()));
            }
        }

        private void fillActivity()
        {
            lblNoActivities.Visible = false;
            txtEstimateTime.Text = "0";
            //ddlTypeTime.DataSource = BuProject.selAllTypeTime();
            //ddlTypeTime.DataTextField = "TypeTimeName";
            //ddlTypeTime.DataValueField = "TypeTimeID";
            //ddlTypeTime.DataBind();

            // Lay projectID qua tham so pid
            int projectID = Int32.Parse(getParam());
            // Truong hop sua project
            if (projectID != 0)
            {
                DataTable listActivity = BuActivity.selActivityByProjectID2(projectID, Session["companyid"].ToString());
                if (listActivity.Rows.Count == 0)
                {
                    lblNoActivities.Visible = true;
                }
                else
                {
                    grvActivity.DataSource = listActivity;
                    grvActivity.DataBind();
                }
            }
        }

        private void fillProjectMember()
        {
            // Lay projectID qua tham so pid
            int projectID = Int32.Parse(getParam());
            txtCost.Text = "0";
            // Truong hop sua project
            if (projectID != 0)
            {

                gvProjectMember.DataSource = BuProject.selStaffMemberProject(projectID, Session["companyid"].ToString());
                gvProjectMember.DataBind();

                ddlMember.DataSource = BuProject.selStaffMemberProjectAdd(projectID, Session["companyid"].ToString());
                ddlMember.DataTextField = "StaffName";
                ddlMember.DataValueField = "StaffID";
                ddlMember.DataBind();
            }
        }

        private void fillTimeUser()
        {
            // Lay projectID qua tham so pid
            int projectID = Int32.Parse(getParam());
            // Truong hop sua project
            if (projectID != 0)
            {
                DataTable tmpTimeUser = BuProject.selTimeUser(projectID, Session["companyid"].ToString());
                if (tmpTimeUser.Rows.Count > 0)
                {
                    gvReportTime.DataSource = tmpTimeUser;
                    gvReportTime.DataBind();
                }
                else
                {
                    // Khong hien thi TimeReport
                    pnlReportTime.Visible = false;
                }
            }
        }
        
        private int totalHour = 0;
        private int totalMinute = 0;
        private int totalEstimateTime = 0;
        protected void grvActivity_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                totalHour += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Hour"));
                totalMinute += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Minute"));
                totalEstimateTime += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ActivityEstimateTime"));
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (totalMinute >= 60)
                {
                    int addHour = totalMinute / 60;
                    totalMinute -= 60 * addHour;
                    totalHour += addHour;
                }
                Label lblSum = (Label)e.Row.FindControl("lblSum");
                lblSum.Text = totalHour.ToString() + "," + totalMinute.ToString() + "m";
                Label lblSumEstimateTime = (Label)e.Row.FindControl("lblSumEstimateTime");
                lblSumEstimateTime.Text = totalEstimateTime.ToString() + "h";
                   
            }
        }

        protected void gvProjectMember_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvProjectMember.EditIndex = e.NewEditIndex;
            fillProjectMember();
        }

        protected void gvProjectMember_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvProjectMember.EditIndex = -1;
            fillProjectMember();
        }

        protected void gvProjectMember_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            EnSP sp = new EnSP();
            try
            {
                sp.spStaffID = Int32.Parse(gvProjectMember.DataKeys[e.RowIndex].Values[0].ToString());
                sp.spProjectID = Int32.Parse(gvProjectMember.DataKeys[e.RowIndex].Values[1].ToString());
                sp.spCostPerHour = float.Parse(((TextBox)gvProjectMember.Rows[e.RowIndex].FindControl("txtCostPerHour")).Text);
                BuProject.updProjectMember(sp, Session["companyid"].ToString());
            }
            catch
            {
                gvProjectMember.EditIndex = -1;
                fillProjectMember();
            }

            gvProjectMember.EditIndex = -1;
            fillProjectMember();
        }

        protected void gvProjectMember_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            EnSP sp = new EnSP();
            sp.spStaffID = Int32.Parse(gvProjectMember.DataKeys[e.RowIndex].Values[0].ToString());
            sp.spProjectID = Int32.Parse(gvProjectMember.DataKeys[e.RowIndex].Values[1].ToString());
            BuProject.delProjectMember(sp, Session["companyid"].ToString());
            fillProjectMember();
        }

        protected void gvProjectMember_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox txtCostPerHour = (TextBox)e.Row.FindControl("txtCostPerHour");
                if (txtCostPerHour != null)
                {
                    txtCostPerHour.Text = gvProjectMember.DataKeys[e.Row.RowIndex].Values[2].ToString();
                }
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int projectID = Int32.Parse(getParam());
            string nameProject = txtProjectName.Text.Trim();
            if (nameProject.Equals(""))
            {
                // Truong hop bo trong ten project
                txtProjectName.CssClass = "input-error";
                lblError.Text = "Không được bỏ trống!";
            }
            else
            {
                // Lay cac tham so
                int projectManager = Int32.Parse(ddlProjectManager.SelectedValue);
                int clientID = Int32.Parse(ddlClient.SelectedValue);
                string projectDescription = txtDescription.Text;
                bool isMember = cbIsMember.Checked;
                bool isComplete = cbIsComplete.Checked;
                string startDate = txtStartDay.Text;
                string endDate = txtEndDay.Text;

                // Chay cac thu thu tuc
                EnProject project = new EnProject();
                project.projectName = nameProject;
                project.projectDescription = projectDescription;
                project.projectClientID = clientID;
                project.projectStartDate = DateTime.ParseExact(startDate, "dd/MM/yyyy", null);
                project.projectEndDate = DateTime.ParseExact(endDate, "dd/MM/yyyy", null);
                project.projectEnable = isComplete;
                project.projectEnableMember = isMember;
                project.projectManager = projectManager;
                project.projectID = projectID;
                BuProject.updProject(project, Session["companyid"].ToString());

                //Response.Redirect("ListProject.aspx");
            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int projectID = Int32.Parse(getParam());
            EnProject project = new EnProject();
            project.projectID = projectID;
            BuProject.delProject(project, Session["companyid"].ToString());
            Response.Redirect("ProjectTree.aspx");
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            int projectID = Int32.Parse(getParam());
            EnActivity activity = new EnActivity();
            activity.activityName = txtActivityName.Text;
            activity.activityEstimateTime = Int32.Parse(txtEstimateTime.Text);
            activity.activityProjectID = projectID;
            activity.activityCode = txtActivityCode.Text;
            //activity.activityTypeTimeID = Int32.Parse(ddlTypeTime.SelectedValue);

            BuProject.insActivity2(activity, Session["companyid"].ToString());
            txtActivityName.Text = String.Empty;
            fillActivity();
        }

        protected void grvActivity_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string currentCommand = e.CommandName;
            int activityID = Int32.Parse(e.CommandArgument.ToString());
            EnActivity activity = new EnActivity();
            activity.activityID = activityID;
            if (currentCommand.Equals("UpLevel"))
            {
                BuProject.upLevel(activity, Session["companyid"].ToString());
            }
            else if (currentCommand.Equals("DownLevel"))
            {
                BuProject.downLevel(activity, Session["companyid"].ToString());
            }
            fillActivity();
        }

        protected void btnAddMember_Click(object sender, EventArgs e)
        {
            EnSP sp = new EnSP();
            sp.spStaffID = Int32.Parse(ddlMember.SelectedValue);
            sp.spProjectID = Int32.Parse(getParam());
            sp.spCostPerHour = float.Parse(txtCost.Text);

            BuProject.insProjectMember(sp, Session["companyid"].ToString());
            txtCost.Text = String.Empty;
            fillProjectMember();
        }

        protected void fillCopyActivity()
        {
            int projectID = Int32.Parse(getParam());
            EnProject project = new EnProject();
            project.projectID = projectID;
            ddlCopyProject.DataSource = BuProject.selProjectExceptIDNew(project, Session["companyid"].ToString());
            ddlCopyProject.DataTextField = "ProjectName";
            ddlCopyProject.DataValueField = "ProjectID";
            ddlCopyProject.DataBind();
        }

        protected void btnCancelCopy_Click(object sender, EventArgs e)
        {

        }

        protected void btnCopyActivity_Click(object sender, EventArgs e)
        {
            int projectID = Int32.Parse(getParam());
            EnProject project = new EnProject();
            try{

                project.projectID = Int32.Parse(ddlCopyProject.SelectedValue);
                BuProject.copyActivity(project, projectID, Session["companyid"].ToString());
                fillActivity();
            }catch{}
        }

 
    }
}